package elsa.tools;

import elsa.bean.ScsPermission;
import elsa.bean.ScsUser;
import elsa.bootmapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    //认证.登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.err.println("--------doGetAuthenticationInfo--------");
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;//获取用户输入的token
        String username = utoken.getUsername();
        ScsUser user = userMapper.findByUsername(username);
        return new SimpleAuthenticationInfo(user, user.getPassword(),this.getClass().getName());//放入shiro.调用CredentialsMatcher检验密码
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal){
        System.err.println("--------doGetAuthorizationInfo--------");
        ScsUser user=(ScsUser) principal.fromRealm(this.getClass().getName()).iterator().next();//获取session中的用户
        System.out.println(user.getUserid());
        List<String> per=new ArrayList<>();
        String role = userMapper.findRole(user.getUserid()).getRole();
        System.out.println(role);
        List<ScsPermission> permissions = userMapper.findPermission(role);
        if(permissions.size()>0) {
            for(ScsPermission permission : permissions) {
                per.add(permission.getPermissionname());
                System.out.println(permission.getPermissionname());
            }
        }
        System.out.print(permissions.size());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermissions(per);//将权限放入shiro中.
        return info;
    }

}
